<template>
  <div class="app-container">
    <!--对象搜索树型列表-->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="产品名称" prop="product">
        <y-select
          v-model="queryParams.product"
          placeholder="请选择产品名称"
          :optionsFunc="listProduct"
        />
      </el-form-item>
      <el-form-item label="影响版本" prop="version">
        <y-select
          v-model="queryParams.version"
          placeholder="请选择影响版本"
          :optionsFunc="listVersion"
          :optionsParams="{ product: queryParams.product, nopaginate: true }"
        />
      </el-form-item>
      <el-form-item label="缺陷编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入缺陷编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="缺陷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入缺陷名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="严重性" prop="gravity">
        <y-select
          v-model="queryParams.gravity"
          placeholder="请选择严重性"
          :options="sys_gravity_level"
        />
      </el-form-item>
      <el-form-item label="缺陷状态" prop="status">
        <y-select
          v-model="queryParams.status"
          placeholder="请选择缺陷状态"
          :options="tms_bug_status"
        />
      </el-form-item>
      <el-form-item label="开发接口人" prop="downer">
        <y-select
          v-model="queryParams.downer"
          placeholder="请选择开发接口人"
          :optionsFunc="listUser"
        />
      </el-form-item>
      <el-form-item label="测试接口人" prop="towner">
        <y-select
          v-model="queryParams.towner"
          placeholder="请选择测试接口人"
          :optionsFunc="listUser"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <y-select
          v-model="queryParams.creator"
          placeholder="请选择创建人"
          :optionsFunc="listUser"
        />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input
          v-model="queryParams.tags"
          placeholder="请输入标签"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--对象操作-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tms:bug:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleEdit"
          v-hasPermi="['tms:bug:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tms:bug:delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['tms:bug:import']"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <y-export
          :url="'tms/bug/export/'"
          :ids="ids"
          :filename="'bug_data'"
          :exportToWord="handleExportToWord"
          v-hasPermi="['tms:bug:export']"
        />
      </el-col>
      <y-right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      />
    </el-row>

    <!--对象列表-->
    <el-table
      ref="tableRef"
      v-loading="loading"
      row-key="id"
      :data="bugList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        reserve-selection
      />
      <el-table-column label="序号" width="100" align="center" type="index">
        <template #default="scope">
          {{ scope.$index + (queryParams.page - 1) * queryParams.limit + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="缺陷编号"
        width="180"
        align="center"
        prop="number"
        v-if="columns[0].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <router-link
            :to="'/tms/bug-info/index/' + scope.row.id"
            class="link-type"
          >
            <span>{{ scope.row.number }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="优先级"
        width="100"
        align="center"
        prop="priority"
        v-if="columns[1].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <y-dict-tag
            :options="sys_priority_level"
            :value="scope.row.priority"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="严重性"
        width="100"
        align="center"
        prop="gravity"
        v-if="columns[2].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <y-dict-tag :options="sys_gravity_level" :value="scope.row.gravity" />
        </template>
      </el-table-column>
      <el-table-column
        label="缺陷名称"
        align="center"
        min-width="300"
        prop="name"
        v-if="columns[3].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{
            `${scope.row.tags.length ? `【${scope.row.tags}】` : ""}${
              scope.row.name
            }`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="所属产品"
        align="center"
        min-width="180"
        prop="product.label"
        v-if="columns[4].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="所属模块"
        align="center"
        width="120"
        prop="module.label"
        v-if="columns[5].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="缺陷类型"
        align="center"
        width="120"
        prop="type"
        v-if="columns[6].visible"
        :show-overflow-tooltip="true"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_bug_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column
        label="影响版本"
        align="center"
        width="120"
        prop="version.label"
        v-if="columns[7].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="缺陷状态"
        align="center"
        width="120"
        prop="status"
        v-if="columns[8].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_bug_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="解决方案"
        align="center"
        width="120"
        prop="resolved_type"
        v-if="columns[9].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag
            :options="tms_bug_resolved_type"
            :value="scope.row.resolved_type"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="激活次数"
        align="center"
        width="120"
        prop="activations"
        v-if="columns[10].visible"
        sortable
      >
      </el-table-column>
      <el-table-column
        label="开发接口人"
        align="center"
        width="120"
        prop="downer.label"
        v-if="columns[11].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="测试接口人"
        align="center"
        width="120"
        prop="towner.label"
        v-if="columns[12].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="创建人"
        width="100"
        align="center"
        prop="creator_name"
        v-if="columns[13].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        v-if="columns[14].visible"
        width="160"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" width="220">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['tms:bug:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.status !== 'resolved'"
            content="激活"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="MagicStick"
              @click="handleActive(scope.row)"
              v-hasPermi="['tms:bug:activated']"
              :disabled="
                !['new', 'closed', 'pending'].includes(scope.row.status)
              "
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="解决" placement="top">
            <el-button
              link
              type="primary"
              icon="CircleCheck"
              @click="handleResolve(scope.row)"
              v-hasPermi="['tms:bug:resolved']"
              :disabled="
                !['activated', 'reactivated'].includes(scope.row.status)
              "
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.status === 'resolved'"
            content="验证"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="Compass"
              @click="handleVerify(scope.row)"
              v-hasPermi="['tms:bug:closed']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="挂起" placement="top">
            <el-button
              link
              type="primary"
              icon="Warning"
              @click="handlePending(scope.row)"
              v-hasPermi="['tms:bug:pending']"
              :disabled="scope.row.status !== 'resolved'"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="评论" placement="top">
            <el-button
              link
              type="primary"
              icon="ChatLineSquare"
              @click="handleComment(scope.row)"
              v-hasPermi="['tms:bug:comment']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['tms:bug:delete']"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--列表分页-->
    <y-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <au-bug
      :id="id"
      v-model="open"
      :title="title"
      :operate="operate"
      :getMethod="getBug"
      :addMethod="addBug"
      :updateMethod="updateBug"
      @submited="submited"
      @close="open = false"
    >
    </au-bug>

    <!-- 添加或修改对话框 -->
    <au-comment
      :id="id"
      v-model="openBugComment"
      :title="title"
      operate="add"
      :getMethod="getBugComment"
      :addMethod="addBugComment"
      :updateMethod="updateBugComment"
      @submited="submited"
      @close="openBugComment = false"
    >
    </au-comment>

    <bug-active
      :id="id"
      v-model="openActiveBug"
      :title="title"
      :getMethod="getBug"
      :updateMethod="updateBug"
      @submited="submited"
      @close="openActiveBug = false"
    >
    </bug-active>

    <bug-verify
      :id="id"
      v-model="openVerifyBug"
      :title="title"
      :getMethod="getBug"
      :updateMethod="updateBug"
      @submited="submited"
      @close="openVerifyBug = false"
    >
    </bug-verify>

    <bug-pending
      :id="id"
      v-model="openPendingBug"
      :title="title"
      :getMethod="getBug"
      :updateMethod="updateBug"
      @submited="submited"
      @close="openPendingBug = false"
    >
    </bug-pending>

    <bug-resolve
      :id="id"
      :product="currentProduct"
      v-model="openResolveBug"
      :title="title"
      :getMethod="getBug"
      :updateMethod="updateBug"
      @submited="submited"
      @close="openResolveBug = false"
    >
    </bug-resolve>

    <!-- 导入对话框-->
    <y-import :upload="upload" @submited="submited" />
  </div>
</template>

<script setup name="产品缺陷">
import { listVersion } from "@/api/pms/version";
import { listBug, getBug, addBug, updateBug, delBug } from "@/api/tms/bug";
import {
  listBugComment,
  getBugComment,
  addBugComment,
  updateBugComment,
  delBugComment,
} from "@/api/tms/bug/comment";
import AuBug from "./components/AuBug";
import AuComment from "./components/AuComment";
import BugActive from "./components/BugActive";
import BugVerify from "./components/BugVerify";
import BugResolve from "./components/BugResolve";
import BugPending from "./components/BugPending";
import { listProduct } from "@/api/pms/product";
import { listUser } from "@/api/sys/user";

const { proxy } = getCurrentInstance();
const {
  tms_bug_status,
  sys_priority_level,
  sys_gravity_level,
  tms_bug_type,
  tms_bug_resolved_type,
} = proxy.useDict(
  "tms_bug_status",
  "sys_priority_level",
  "sys_gravity_level",
  "tms_bug_type",
  "tms_bug_resolved_type"
);

const route = useRoute();

const id = ref(null);
const ids = ref([]);
const open = ref(false);
const title = ref("");
const total = ref(0);
const single = ref(true);
const loading = ref(false);
const multiple = ref(true);
const operate = ref("add");
const dateRange = ref([]);
const showSearch = ref(false);
const bugList = ref([]);
const openActiveBug = ref(false);
const openVerifyBug = ref(false);
const openResolveBug = ref(false);
const openPendingBug = ref(false);
const openBugComment = ref(false);
const currentProduct = ref(null);

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/tms/bug/import/",
});

const columns = ref([
  { key: 0, label: `缺陷编号`, visible: true },
  { key: 1, label: `优先级`, visible: true },
  { key: 2, label: `严重性`, visible: true },
  { key: 3, label: `缺陷名称`, visible: true },
  { key: 4, label: `所属产品`, visible: true },
  { key: 5, label: `所属模块`, visible: false },
  { key: 6, label: `缺陷类型`, visible: false },
  { key: 7, label: `影响版本`, visible: false },
  { key: 8, label: `缺陷状态`, visible: true },
  { key: 9, label: `解决方案`, visible: true },
  { key: 10, label: `激活次数`, visible: false },
  { key: 11, label: `测试接口人`, visible: true },
  { key: 12, label: `开发接口人`, visible: true },
  { key: 13, label: `创建人`, visible: true },
  { key: 14, label: `创建时间`, visible: true },
]);

const data = reactive({
  queryParams: {
    product: route.query.product,
    version: route.query.version,
    module: route.query.module,
    name: undefined,
    page: 1,
    limit: 10,
  },
});

const { queryParams } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  listBug(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      loading.value = false;
      bugList.value = response.data;
      total.value = response.total;
    }
  );
}

/** 搜索按钮操作 */
function handleQuery(params = {}) {
  if (params.value) {
    queryParams.value = params.value;
  }
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  operate.value = "add";
  open.value = true;
  title.value = "添加缺陷";
}

/** 修改按钮操作 */
function handleEdit(row) {
  id.value = row.id || ids.value;
  operate.value = "update";
  open.value = true;
  title.value = "修改缺陷";
}

/** 激活按钮操作 */
async function handleActive(row) {
  id.value = row.id || ids.value;
  openActiveBug.value = true;
  title.value = "激活缺陷";
}

/** 解决按钮操作 */
function handleResolve(row) {
  id.value = row.id || ids.value;
  currentProduct.value = row.product.value;
  openResolveBug.value = true;
  title.value = "解决缺陷";
}

/** 验证按钮操作 */
function handleVerify(row) {
  id.value = row.id || ids.value;
  openVerifyBug.value = true;
  title.value = "验证缺陷";
}

/** 挂起按钮操作 */
function handlePending(row) {
  id.value = row.id || ids.value;
  openPendingBug.value = true;
  title.value = "挂起缺陷";
}

/** 评论按钮操作 */
function handleComment(row) {
  operate.value = "add";
  id.value = row.id || ids.value;
  openBugComment.value = true;
  title.value = "评论缺陷";
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "缺陷导入";
  upload.open = true;
}

/** 导出为PDF */
function handleExportToWord() {
  try {
    let url = "tms/bug/export_to_word/";
    let filename = `缺陷报表_${Date.now()}.docx`;
    let params = { ids: ids.value };
    proxy.download(url, filename, params);
  } catch (error) {
    console.error("Error in generate report document:", error);
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    if (row.id) {
      await proxy.$modal.confirm(`确认是否删除 "${row.name}" ？`);
    } else {
      await proxy.$modal.confirm("确认是否删除所有已勾选信息？");
    }
    ids.value = row.id ? [row.id] : ids.value;
    await delBug(ids.value);
    proxy.$modal.msgSuccess("删除成功");
    proxy.$refs.tableRef.clearSelection();
    getList();
  } catch (error) {
    console.error(error);
  }
}

/** 添加/修改对象后触发事件 */
function submited() {
  getList();
}

/** Expose方法 */
defineExpose({
  handleQuery,
});

onMounted(() => {
  getList();
});
</script>
